#!/usr/bin/env node

const http=require('http'),
      fs=require('fs'),
      qs=require('querystring'),
      path=require('path'),
      log=console.log;

const errorPage=`
<!DOCTYPE html>
<html>
<head>
  <meta charset="UTF-8">
  <title>Error</title>
</head>
<body>
  <h1>sorry, here is noting</h1>
  <a href='/'>back to upload images</a>
</body>
`


http.createServer((req,res)=>{
  printRequest(req);

  if(req.method==='GET' && req.url==='/'){
    show(res,uploadPage());
    return;
  }

  if(req.method==='GET' && req.url.split('/')[1]==='images'){
    sendPic(req,res);
    return;
  }

  if(req.method==='POST' && req.url==='/upload'){
    req.setEncoding('binary');
    
    let file;

    req.on('data',data=>file+=data);
    req.on('end',()=>{
      if(writePic(file)){
        show(res,uploadPage());
      }else{
        show(res,errorPage);
      }
    });

    return;
  }

  show(res,errorPage);
}).listen(8080);





